<?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Description: 启动接口
 *
 * @author      Eden
 * @datetime    2016/11/29 19:58
 * @copyright   Beijing CmsTop Technology Co.,Ltd.
 */

class Common_Model extends API_Model
{

    /**
     * 参数
     * @var array
     */
    private $params = array();

    /**
     * 配置
     * @var array
     */
    private $conf = array();

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 主函数
     * @param array $params
     */
    public function run(Array $params)
    {
        $this->_checkParams($params);
        $this->params = $params;
        $this->getSettingInfo();

        $return = array(
            'general' => $this->_getGeneral(),
            'upgrade' => $this->_getUpgrade(),
            'contact' => $this->_getContact(),
            'about' => $this->_getAbout(),
            'searchKeyword' => $this->_getSearchKeyword(),
            'expressCost' => $this->_getShippingCosts()
        );

        $this->doAfter();

        $this->output->send(array(
            'state' => true,
            'data' => $return
        ));
    }

    /**
     * 物流费用
     * @return array
     */
    private function _getShippingCosts()
    {
        $default = array(
            'payer' => 'seller',
            'costs' => new stdClass()
        );
        // 前期只考虑到统一的价格的情况,没有进行区域区分
        $db = clone($this->db);
        $q = $db->get_where('express_template', array('using' => 1));
        $row = $q->row_array();
        if (!$row) {
            return $default;
        }

        if ($row['payer'] == 'seller') {
            return $default;
        }

        $payer = $row['payer'];
        if ($row['payType'] == 'weight') {
            $q = $this->db->get_where('express_weight', array('tmpId' => $row['id']));
            $row = $q->row_array();
            if (empty($row)) {
                return $default;
            }
            $default['payer'] = $payer;
            $default['costs'] = array(
                'firstWeight' => doubleval($row['firstWeight']),
                'firstCost' => doubleval($row['firstCost']),
                'incrWeight' => doubleval($row['incrWeight']),
                'incrCost' => doubleval($row['incrCost'])
            );
        }

        return $default;
    }

    /**
     * 关键词
     * @return array
     */
    private function _getSearchKeyword()
    {
        $q = $this->db->select('keyword')
            ->order_by('times', 'DESC')
            ->limit(10)
            ->get('search');
        $keywords = [];
        if ($rows = $q->result_array()) foreach($rows as $item) {
            array_push($keywords, $item['keyword']);
        }
        return $keywords;
    }

    /**
     * App描述
     * 隐私说明
     * @return array
     */
    private function _getAbout()
    {
        return array(
            'appDescription' => $this->_getDesc(),
            'privicy' => $this->_getPrivicy()
        );
    }

    /**
     * 隐私声明
     * @return mixed
     */
    private function _getPrivicy()
    {
        $desc = value($this->conf['privicy'], 'content');
        return $this->load->view('app/start/privicy.html', array('content' => $desc), true);
    }

    /**
     * App 描述
     * @return mixed
     */
    private function _getDesc()
    {
        $desc = value($this->conf['description'], 'content');
        return $this->load->view('app/start/description.html', array('content' => $desc), true);
    }

    /**
     * 获取联系方式
     * @return array
     */
    private function _getContact()
    {
        $data = array();
        $contact = $this->getS('system', 'contact');
        $data['telePhone'] = value($contact, 'telphone', '');
        $data['phone'] = value($contact, 'phone', '');
        $data['address'] = value($contact, 'address', '');
        $data['qq'] = value($contact, 'qq', '');
        $data['zipCode'] = value($contact, 'zipCode', '');
        $data['email'] = value($contact, 'email', '');
        return $data;
    }

    /**
     * 升级信息
     * @return array
     */
    private function _getUpgrade()
    {
        $return = array(
            'version' => '',
            'description' => '',
            'url' => ''
        );

        if (!empty($this->conf['download'])) {
            $type = $this->params['type'];
            $conf = value($this->conf['download'], $type, array());
            $return['version'] = value($conf, 'version');
            $return['description'] = value($conf, 'description', '');
            $return['url'] = value($conf, 'address');
        }

        return $return;
    }

    /**
     * 能用信息
     * @return array
     */
    private function _getGeneral()
    {
        $general = $this->conf['general'];
        $nav = $slider = array();
        $nav['appName'] = value($general, 'appName', '');
        $nav['logo'] = thumb(value($general, 'logo', ''));
        $type = value($general, 'slideType', 'hand');
        $slide['slideNum'] = intval(value($general, 'slideNum', 0));
        $slide['slideType'] = $type;
        $slide['slideTimer'] = $type == 'auto' ? intval(value($general, 'slideTimer')) : 0;

        $advInfo = value($this->conf['adv'], 'imageUrl');
        $adv['imageUrl'] = thumb($advInfo, 640, 1136);

        return array(
            'nav' => $nav,
            'slide' => $slide,
            'adv' => $adv
        );
    }

    /**
     * 获取必须的setting 数据
     */
    private function getSettingInfo()
    {
        try {
            $sDb = clone($this->db);
            $keys = array('general', 'download', 'adv', 'privicy', 'description', 'privicy');
            foreach($keys as $k) {
                $this->conf[$k] = array();
            }
            $query = $sDb->where('use', 'mobile')->where_in('key', $keys)->get('setting');
            $res = $query->result_array();
            if ($res) foreach($res as $item) {
                $key = $item['key'];
                $this->conf[$key] = json_decode($item['value'], true);
            }
        } catch(PDOException $e) {
            $this->sendError('配置错误');
        }
    }

    /**
     * 获取指定 Config
     * @param string $use
     * @param string $key
     * @return array
     */
    private function getS($use = 'mobile', $key = '')
    {
        if (empty($key)) {
            return array();
        }

        $sDb = clone($this->db);
        $query = $sDb->get_where('setting', array(
            'use' => $use, 'key' => $key
        ));
        $res = $query->row_array();
        if (empty($res)) {
            return array();
        } else {
            return json_decode($res['value'], true);
        }
    }

    /**
     * 发送错误信息
     * @param $error
     */
    private function sendError($error)
    {
        $this->output->send(array(
            'state' => false,
            'error' => !empty($error) ? $error : '参数错误'
        ));
    }

    /**
     * 检查参数
     * @param $params
     */
    private function _checkParams($params)
    {
        if (empty($params['deviceId'])) {
            $this->output->send(array(
                'state' => false,
                'error' => '参数错误'
            ));
        }
    }

    private function doAfter()
    {
        // 统计启动信息和安装信息
        $this->anaInstallation();
    }

    /**
     * 统计安装量
     */
    private function anaInstallation()
    {
        $deviceId = value($this->params, 'deviceId');
        $insDb = clone($this->db);
        $installAdd = false;

        // 安装
        $query = $insDb->get_where('analytics_app_installation', array('deviceId' => $deviceId));
        if (!$query->row_array()) {
            $deviceData = array('deviceId' => $deviceId, 'type' => $this->params['type'], 'created' => dateTime());
            if ($insDb->insert('analytics_app_installation', $deviceData)) {
                $installAdd = true;
            }
        }

        $date = date('Y-m-d');
        $anaDb = clone($this->db);
        $query = $anaDb->get_where('analytics_daily', array('date' => $date));
        $row = $query->row_array();
        if ($row) {
            $anaDb->set('startUpTimes', 'startUpTimes + 1', false);
            if ($installAdd) {
                $anaDb->set('installTimes', 'installTimes + 1', false);
                if ($this->params['type'] == 'ios') {
                    $anaDb->set('iosInstallTimes', 'iosInstallTimes + 1', false);
                } else {
                    $anaDb->set('androidInstallTimes', 'androidInstallTimes + 1', false);
                }
            }
            $anaDb->where('date', $date);
            $anaDb->update('analytics_daily');
        } else {
            // 插入
            $dailyData['date'] = $date;
            $dailyData['startUpTimes'] = 1;
            $dailyData['installTimes'] = $installAdd ? 1 : 0;
            $anaDb->insert('analytics_daily', $dailyData);
        }

    }
}
